package com.example.shittime;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;

import org.xmlpull.v1.XmlSerializer;

import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Xml;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.DatePicker;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.googleapis.extensions.android.gms.auth.UserRecoverableAuthIOException;
import com.google.api.client.http.FileContent;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

public class ShitActivity extends Activity {

	static final int REQUEST_ACCOUNT_PICKER = 1;
	static final int REQUEST_AUTHORIZATION = 2;
	static final int CAPTURE_IMAGE = 3;

	private static Uri fileUri;
	private static Drive service;
	private GoogleAccountCredential credential;

	private TextView hoursView;
	private SeekBar seekBar;
	private DatePicker datePicker;
	private Spinner spinner;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// credential = GoogleAccountCredential.usingOAuth2(this,
		// DriveScopes.DRIVE);
		// startActivityForResult(credential.newChooseAccountIntent(),
		// REQUEST_ACCOUNT_PICKER);
		spinner = (Spinner) findViewById(R.id.spinner1);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.activities, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);

		datePicker = (DatePicker) findViewById(R.id.datePicker1);
		hoursView = (TextView) findViewById(R.id.textView5);
		seekBar = (SeekBar) findViewById(R.id.seekBar1);
		seekBar.setMax(24);
		seekBar.setProgress(1);
		hoursView.setText("1 h");
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				hoursView.setText(seekBar.getProgress() + " h");

			}
		});

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		switch (requestCode) {
		case REQUEST_ACCOUNT_PICKER:
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				if (accountName != null) {
					credential.setSelectedAccountName(accountName);
					service = getDriveService(credential);
				}
			}
			break;
		case REQUEST_AUTHORIZATION:
			if (resultCode == Activity.RESULT_OK) {
				saveFileToDrive();
			} else {
				startActivityForResult(credential.newChooseAccountIntent(),
						REQUEST_ACCOUNT_PICKER);
			}
			break;
		}
	}

	private void saveFileToDrive() {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// File's binary content
					java.io.File fileContent = new java.io.File(fileUri
							.getPath());
					FileContent mediaContent = new FileContent("image/jpeg",
							fileContent);

					// File's metadata.
					File body = new File();
					body.setTitle(fileContent.getName());
					body.setMimeType("image/jpeg");

					File file = service.files().insert(body, mediaContent)
							.execute();
					if (file != null) {
						showToast("Photo uploaded: " + file.getTitle());
					}
				} catch (UserRecoverableAuthIOException e) {
					startActivityForResult(e.getIntent(), REQUEST_AUTHORIZATION);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		t.start();
	}

	private Drive getDriveService(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	public void saveData(View v) {
		if (isExternalStorageReadable()) {

			java.io.File file = new java.io.File(Environment
					.getExternalStorageDirectory().toString() + "/ShitTime");
			if (!file.exists()) {
				file.mkdir();
			}

			java.io.File xmlFile = new java.io.File(file, "reporte.xml");
			if (!xmlFile.exists()) {
				try {
					xmlFile.createNewFile();
					FileOutputStream fos = openFileOutput("reporte.xml",
							Context.MODE_WORLD_WRITEABLE);
					OutputStreamWriter osw = new OutputStreamWriter(fos);
					osw.append("<xml>FUNCIONA POR DIOS</xml>");
					osw.close();

					// PrintStream print = new PrintStream(fos);
					// print.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
					// print.println("<xml>");
					// print.println("<reports>");
					// print.println("<report>");
					// print.println("<date>" + datePicker.getDayOfMonth() + "-"
					// + datePicker.getMonth() + "-"
					// + datePicker.getYear() + "</date>");
					// print.println("<activity>"
					// + spinner.getSelectedItem().toString()
					// + "</activity>");
					// print.println("<time>" + seekBar.getProgress() +
					// "</time>");
					// print.println("</report>");
					// print.println("</reports>");
					// print.println("</xml>");
					//
					// print.close();
					// String text = "<xml></xml>";
					// fos.write(text.getBytes("UTF-8"));
					fos.close();

					Toast.makeText(this, "Primer dato guardado",
							Toast.LENGTH_SHORT).show();
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				Toast.makeText(this, "Otro dato guardado", Toast.LENGTH_SHORT)
						.show();
			}

		} else {
			Toast.makeText(this, "NO hay SD! Estamos jodidos!",
					Toast.LENGTH_LONG).show();
		}

	}

	public void lanzarDistracciones(View v) {

	}

	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	/* Checks if external storage is available to at least read */
	public boolean isExternalStorageReadable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)
				|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

}
